//
//  SelectContactsVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/27.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "SelectContactsVC.h"

#import "ContactHelper.h"

#import "AdresBookSectionModel.h"
#import "ContactsDisplayCell.h"
@interface SelectContactsVC ()

@property (nonatomic, strong) NSMutableArray<AdresBookSectionModel *> *dataModels;


@property (nonatomic, strong) NSMutableArray<AdresBookSectionModel *> *lastDataModels;


/** <#note#> */
@property (nonatomic, strong) NSArray<NSString *> *keys;

@end

@implementation SelectContactsVC

- (NSArray<NSString *> *)keys{
    
    if (!_keys) {
        _keys = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#"];
    }
    return _keys;
}


- ( NSMutableArray<AdresBookSectionModel *> *)dataModels{
    
    if (!_dataModels) {
        _dataModels = [NSMutableArray arrayWithCapacity:27];
        for (int i = 0; i < 27; i ++) {
            AdresBookSectionModel *temp = [[AdresBookSectionModel alloc]init];
            
            temp.models = [NSMutableArray array];
            
            temp.setionName = self.keys[i];
            
            [_dataModels addObject:temp];
        }
    }
    
    return _dataModels;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = randomColor;
    
    self.navigationItem.title = @"通讯录";
    
    [self setNav];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.plainTableView.backgroundColor = [UIColor whiteColor];
    
    self.plainTableView.rowHeight = 44;
    

    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ContactsDisplayCell class]) bundle:nil] forCellReuseIdentifier:[ContactsDisplayCell identifierStr]];
//    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([CreatAddressTwoCell class]) bundle:nil] forCellReuseIdentifier:[CreatAddressTwoCell identifierStr]];
    
//    MJWeakSelf
//    self.plainTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
//
//        [weakSelf loadData];
//
//    }];
//
//    [weakSelf.plainTableView.mj_header beginRefreshing];
    

    [self loadData];

}

- (void)loadData{
    
    
    MJWeakSelf;
    
    [_contactHelper fetchContacts:^(BOOL granted, NSArray<Contacter *> *contacters) {
        
        if (!granted) {
            // 弹出授权未通过
            
            UIAlertController *contr = [UIAlertController alertControllerWithTitle:@"提示" message:@"同步前请去设置中心，开启人脉网访问通讯录权限。" preferredStyle:UIAlertControllerStyleAlert];
            
            //    MJWeakSelf;
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                
            }];
            
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            
            [contr addAction:action2];
            [contr addAction:action1];
            
            [weakSelf presentViewController:contr animated:YES completion:nil];
            
            
            return;
            
        }
        
        if (contacters.count > 0) {
            
            [weakSelf editContacts:contacters];
            
            self.dataModels = nil;
            
            for (Contacter *item in contacters) {
                for (AdresBookSectionModel *setionModel in weakSelf.dataModels) {
                    if ([item.letter isEqualToString:setionModel.setionName]) {
                        [setionModel.models addObject:item];
                    }
                }
            }
            
            NSMutableArray<AdresBookSectionModel *> *lastArray = [NSMutableArray array];
            for (AdresBookSectionModel *lastModel in weakSelf.dataModels) {
                if (lastModel.models.count > 0) {
                    [lastArray addObject:lastModel];
                }
                
            }
            
             weakSelf.lastDataModels = lastArray;
            
            [weakSelf.plainTableView.mj_header endRefreshing];
            
            [weakSelf.plainTableView reloadData];
        } else {
            [weakSelf.plainTableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:@"读取联系人失败!"];

        }
        
   
        
        
        
    }];
    
    
    
}

- (void)editContacts:(NSArray<Contacter *> *)contacts{
    
    
    for (Contacter *temp in contacts) {
        NSString *str = [self getFirstLetterFromString:temp.name];
        temp.letter = str;
    }
    
    
}


//获取字符串首字母(传入汉字字符串, 返回大写拼音首字母)
- (NSString *)getFirstLetterFromString:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *strPinYin = [str capitalizedString];
    //获取并返回首字母
    return [strPinYin substringToIndex:1];
}

- (void)setNav{
    
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateHighlighted];
    
    [but addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    
    but.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //        but.backgroundColor = [UIColor redColor];
    
    but.frame = CGRectMake(0, 0, 44, 44);
    but.contentEdgeInsets = UIEdgeInsetsMake(11, -10, 11, 22);
    
    UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc]initWithCustomView:but];
    
    self.navigationItem.leftBarButtonItem = returnButtonItem;
    
    
    
}

- (void)back{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.lastDataModels == nil) {
        return 0;
    }
    
    return  self.lastDataModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.lastDataModels == nil) {
        return 0;
    }
    
    return  self.lastDataModels[section].models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    

        
    ContactsDisplayCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ContactsDisplayCell identifierStr]];
    
    
    tableCell.name = self.lastDataModels[indexPath.section].models[indexPath.row].name;
        
        //    tableCell.model = self.dataModels[indexPath.section];
        
    return tableCell;
        
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 36;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *temp = [[UIView alloc]init];
    
    temp.backgroundColor = viewBgGrey;
    
    UILabel *label = [[UILabel alloc]init];
    
    label.textColor = [UIColor blackColor];
    
    label.font = MYFONT(17);
    
    label.text = self.lastDataModels[section].setionName;
    
    [label sizeToFit];
    
    label.left = 20;
    
    label.centerY = 18;
    
    [temp addSubview:label];
    
    return temp;
}


- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    
    if (self.lastDataModels == nil) {
        return  @[];
    }
    
    
    return [self.lastDataModels valueForKeyPath:@"setionName"];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSString *name = self.lastDataModels[indexPath.section].models[indexPath.row].name;
    
    if (self.lastDataModels[indexPath.section].models[indexPath.row].phones.count > 0) {
        
        NSString *mobile = self.lastDataModels[indexPath.section].models[indexPath.row].phones[0];
        
        self.infoModel.consigner = name;
        
        self.infoModel.mobile = mobile;
        
    }else{
        
        self.infoModel.consigner = name;

        
    }
    



    [[NSNotificationCenter defaultCenter]postNotificationName:@"DidSelectNameAndPhone" object:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end
